package com.keepers.repair.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.keepers.repair.R;
import com.keepers.repair.activity.MainNewActivity;
import com.keepers.repair.aidl.IMainAidlInterface;
import com.keepers.repair.aidl.IMainCallback;
import com.keepers.repair.aidl.INotNetworkCallback;
import com.keepers.repair.aidl.IPlayAidlCallback;
import com.keepers.repair.helper.MediaPlayHelper;
import com.keepers.repair.helper.SpHelper;
import com.keepers.repair.net.HttpUtil;
import com.keepers.repair.net.LogUtil;
import com.keepers.repair.tcp.ResponseCallback;
import com.keepers.repair.tcp.TCPClient;
import com.keepers.repair.utils.AlertToast;
import com.keepers.repair.utils.CollectionUtil;
import com.keepers.repair.utils.MsgType;
import com.keepers.repair.utils.UtilsKt;

import java.io.File;
import java.util.Calendar;
import java.util.List;

import io.reactivex.functions.Action;

/**
 * auth aboom
 * date 2018/10/31
 */
public class SocketService extends Service {

    public static  TCPClient             tcpClient;
    private static MediaPlayHelper       mediaPlayHelper;
    private        PowerManager.WakeLock wakeLock;
    private        IPlayAidlCallback     iPlayAidlCallback;
    private        INotNetworkCallback   iNotNetworkCallback;

    public IBinder binder = new IMainAidlInterface.Stub() {

        @Override
        public void sendMessage(String msg) {
            send(msg, "Text");
        }

        @Override
        public void sendVoice(String path) {
            send(path, "Audio");
        }

        @Override
        public void setReceivedCallback(IMainCallback callback) {
        }

        @Override
        public void clearReceivedCallback() {

        }

        @Override
        public String getUnreadMessage() {
            return null;
        }

        @Override
        public void closeTcp() {
            if (tcpClient != null) {
                tcpClient.closeTcp();
            }
        }

        @Override
        public void initTcp() {
            if (tcpClient != null && tcpClient.isConnected()) {
                return;
            }
            initSocket();
        }

        @Override
        public void setPlayCallback(IPlayAidlCallback callback) {
            iPlayAidlCallback = callback;
        }

        @Override
        public void setNetWorkCallback(INotNetworkCallback callback) {
            LogUtil.e("binder setNetWorkCallback");
            iNotNetworkCallback = callback;
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    private static ResponseCallback responseCallback = new ResponseCallback() {
        @Override
        public void onRec() {
            MyRecParse myRecParse = new MyRecParse();
            List<String> parse = myRecParse.parse();
            if (CollectionUtil.isNotEmpty(parse)) {
                for (String msg : parse) {
                    UtilsKt.safelyTask(new Action() {
                        @Override
                        public void run() throws Exception {
                            AlertToast.show("收到消息..." + msg);
                        }
                    });
                    playAudio(msg);
                }
            }
        }

        @Override
        public void onFail(Throwable throwable) {
            LogUtil.e("response handlerError:" + throwable.getMessage());
            if (UtilsKt.isNetworkConnected() && SpHelper.getLoginUserInfo() != null) {
                initSocket();
            }
        }
    };

    private static synchronized void playAudio(String msg) {
        if (TextUtils.isEmpty(msg)) {
            return;
        }
        JSONObject parseObject = JSONObject.parseObject(msg);
        String type = parseObject.getString("MType");
        if (MsgType.AUDIO.getValue().equals(type)) {
            String audio = parseObject.getString("Content");
            String name = parseObject.getString("FromUserName");
            if (!TextUtils.isEmpty(audio)) {
                String[] split = audio.split(File.separator);
                String fileName = split[split.length - 1];
                mediaPlayHelper.down(name, fileName);
            }
        }
    }

    private BroadcastReceiver netWorkStateReceiver = new BroadcastReceiver() {

        private boolean isNetwork = true;

        @Override
        public void onReceive(Context context, Intent intent) {
            boolean networkConnected = UtilsKt.isNetworkConnected();
            LogUtil.e(" netWorkStateReceiver : " + networkConnected);
            if (networkConnected) {
                if (!isNetwork && !tcpClient.isConnected() && SpHelper.getLoginUserInfo() != null) {
                    initSocket();
                }
                isNetwork = true;
            } else {
                tcpClient.closeTcp();
                isNetwork = false;
            }
            if (iNotNetworkCallback != null) {
                try {
                    iNotNetworkCallback.callback(networkConnected);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    private void initNetworkReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkStateReceiver, filter);
    }

    public static void initSocket() {
        if (SpHelper.getLoginUserInfo() == null) {
            return;
        }
        if (tcpClient != null) {
            tcpClient.closeTcp();
        }
        String currentHttpHost = SpHelper.getCurrentHttpHost();
        if (TextUtils.isEmpty(currentHttpHost)) {
            currentHttpHost = HttpUtil.HTTP_HOST;
        }
        tcpClient = TCPClient.build()
                .server(currentHttpHost, 7000)
                .breath(new MsgSender("心跳", "Heart").parse(), 270 * 1000);
        tcpClient.onResponse(responseCallback);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("aa", "SocketService onCreate ");
//        initNetworkReceiver();
        initSocket();
        initNotification();
//        getLock(this);
        mediaPlayHelper = new MediaPlayHelper();
        mediaPlayHelper.setOnPlayListener((userName, playPath) -> {
            if (iPlayAidlCallback != null) {
                try {
                    iPlayAidlCallback.onPlay(userName, playPath);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtil.e("socketService onStartCommand");
//        if (tcpClient == null || !tcpClient.isConnected()) {
//            if (UtilsKt.isNetworkConnected()) {
//                LogUtil.e(" onStartCommand initSocket");
//                //42.236.82.246
//                initSocket();
//            }
//        }
        if (UtilsKt.isNetworkConnected()) {
            if (tcpClient == null || !tcpClient.isConnected()) {
                LogUtil.e("socketService onStartCommand initSocket");
                initSocket();
            }
        } else {
            LogUtil.e(" onStartCommand closeTcp");
            tcpClient.closeTcp();
        }
//        startForeground(1, new Notification());
//        //绑定建立链接
//        bindService(new Intent(this, SocketInnerService.class),
//                mServiceConnection, Context.BIND_IMPORTANT);
        return START_STICKY;
    }

//    private ServiceConnection mServiceConnection = new ServiceConnection() {
//        @Override
//        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
//            LogUtil.e("SocketService:建立链接");
//        }
//
//        @Override
//        public void onServiceDisconnected(ComponentName componentName) {
//            startService(new Intent(SocketService.this, SocketInnerService.class));
//            bindService(new Intent(SocketService.this, SocketInnerService.class),
//                    mServiceConnection, Context.BIND_IMPORTANT);
//        }
//    };


    synchronized private void getLock(Context context) {
        if (wakeLock == null) {
            LogUtil.e("get lock");
            PowerManager mgr = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            if (mgr != null) {
                wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, SocketService.class.getName());
                wakeLock.setReferenceCounted(true);
                Calendar c = Calendar.getInstance();
                c.setTimeInMillis((System.currentTimeMillis()));
                int hour = c.get(Calendar.HOUR_OF_DAY);
                if (hour >= 23 || hour <= 6) {
                    wakeLock.acquire(5000);
                } else {
                    wakeLock.acquire(300000);
                }
            }
        }
    }

    synchronized private void releaseLock() {
        if (wakeLock != null) {
            if (wakeLock.isHeld()) {
                wakeLock.release();
                LogUtil.e("release lock");
            }
            wakeLock = null;
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
//        releaseLock();
        LogUtil.e(" SocketService onDestroy");
    }

//    /**
//     * 给 API >= 18 的平台上用的灰色保活手段
//     */
//    public static class SocketInnerService extends Service {
//
//        @Override
//        public void onDestroy() {
//            super.onDestroy();
//            LogUtil.e(" SocketInnerService onDestroy");
//        }
//
//        @Override
//        public int onStartCommand(Intent intent, int flags, int startId) {
//            startForeground(1, new Notification());
//            bindService(new Intent(this, SocketService.class),
//                    serviceConnection, Context.BIND_IMPORTANT);
//            return START_STICKY;
//        }
//
//        private ServiceConnection serviceConnection = new ServiceConnection() {
//            @Override
//            public void onServiceConnected(ComponentName name, IBinder service) {
//                LogUtil.e("SocketInnerService:建立链接");
//
//            }
//
//            @Override
//            public void onServiceDisconnected(ComponentName name) {
//                startService(new Intent(SocketInnerService.this, SocketService.class));
//                bindService(new Intent(SocketInnerService.this, SocketService.class),
//                        serviceConnection, Context.BIND_IMPORTANT);
//            }
//        };
//
//        @Nullable
//        @Override
//        public IBinder onBind(Intent intent) {
//            return new IMainAidlInterface.Stub() {
//                @Override
//                public void sendMessage(String msg) {
//                }
//
//                @Override
//                public void sendVoice(String path) {
//                }
//
//                @Override
//                public void setReceivedCallback(IMainCallback callback) {
//                }
//
//                @Override
//                public void clearReceivedCallback() {
//                }
//
//                @Override
//                public String getUnreadMessage() {
//                    return null;
//                }
//
//                @Override
//                public void closeTcp() {
//
//                }
//
//                @Override
//                public void initTcp() {
//
//                }
//
//                @Override
//                public void setPlayCallback(IPlayAidlCallback callback) {
//
//                }
//
//                @Override
//                public void setNetWorkCallback(INotNetworkCallback callback) {
//
//                }
//            };
//        }
//    }

    private void initNotification() {
//        String name = getString(R.string.app_name);
//        Intent notificationIntent = new Intent(this, MainNewActivity.class);
//        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
//                notificationIntent, 0);
//        Notification notification = new NotificationCompat.Builder(this)
//                .setContentTitle(name)
//                .setContentText(ServiceState.NORMAL.getStr())
//                .setSmallIcon(R.mipmap.ic_launcher)
//                .setContentIntent(pendingIntent)
//                .setPriority(Notification.PRIORITY_MIN)// 设置该通知优先级
//                .build();
//        notification.flags = Notification.FLAG_ONGOING_EVENT;
//        notification.flags |= Notification.FLAG_NO_CLEAR;
//        notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
//        startForeground(0x111, notification);
//
        NotificationManager notificationManager = (NotificationManager) this
                .getSystemService(NOTIFICATION_SERVICE);
        Notification.Builder builder = new Notification.Builder(this);
        Intent intent = new Intent(this, MainNewActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);
        builder.setWhen(System.currentTimeMillis());// 设置通知来到的时间
        builder.setSmallIcon(R.mipmap.ic_launcher);// 设置图标
        builder.setContentTitle("检修应用");// 设置通知的标题
        builder.setContentText("检修应用运行中");// 设置通知的内容
        builder.setOngoing(true);
        Notification notification = builder.build();
        notification.flags = Notification.FLAG_ONGOING_EVENT;
        notification.flags |= Notification.FLAG_NO_CLEAR;
        notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
        if (notificationManager != null) {
            notificationManager.notify(0x111, notification);
        }
    }

    private void send(String message, String msgType) {
        if (!UtilsKt.isNetworkConnected()) {
            LogUtil.e("send isNetworkConnected not");
            AlertToast.show("请检查网络");
            tcpClient.closeTcp();
            return;
        }
        byte[] parse = new MsgSender(message, msgType).parse();
        tcpClient.request(parse);
    }


    public static void startSocketService(Context context) {
        context = context.getApplicationContext();
        LogUtil.e("_SPI_SERVICE _KeeperService_ startSocketService()-S-");
        context.startService(new Intent(context, SocketService.class));
        LogUtil.e("_SPI_SERVICE _KeeperService_ startSocketService()-E-");
    }
}
